//
//  MainTabBar.swift
//  WeiboProject
//
//  Created by amos on 16/1/18.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

class MainTabBar: UITabBar {


    //写作按钮点击事件处理
    var composeBtnClourse : (()->())?
    
    class func mainTabBar() -> MainTabBar {
        return MainTabBar()
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        //2. 添加自定义 button
        let addBtn : UIButton = UIButton()
        addBtn.titleLabel?.text = "哈哈"
        
        
        
        //2.1 设置 normal 下的背景图片
        addBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        
        //2.2 设置 highlight 下的背景图片
        addBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //2.3 设置 normal 下的图片
        addBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        //2.4 设置 highlight 下的图片
        addBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        
        //2.5 设置自适应--根据背景图片确定大小
        addBtn.sizeToFit()
        
        //2.6 设置位置
        self.addSubview(addBtn)
        
        //2.7 添加事件
        addBtn.addTarget(self, action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        
    }
    
    @objc private func composeBtnClick(){
        //调用闭包---控制器响应
        composeBtnClourse?()
    }

    override func layoutSubviews() {
        
        super.layoutSubviews()
        //1.设置子控件
        
        var index = 0
        let w = frame.width * 0.2
        
        for view in self.subviews{

            if view.isKindOfClass(NSClassFromString("UIButton")!.self){
                //2.设置 位置
                view.center = CGPointMake(frame.width * 0.5, frame.height * 0.5)
                continue
            }
        
            if view.isKindOfClass(NSClassFromString("UITabBarButton")!.self){
                
                //1.设置宽度为 tabBar 的五分之一
                
                view.frame.size.width = w
                
                //2.设置 位置
                view.frame.origin.x = w * CGFloat(index)
                index++
                
                if index == 2 {
                    index++
                }
                
            }
            
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
